package no.hib.bridge.connectors;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import no.hib.bridge.DAO.BridgeAccessDAO;
import no.hib.bridge.beans.BoardInfoBean;
import no.hib.bridge.beans.PlayerInfoBean;
import no.hib.bridge.beans.ResultBean;
import no.hib.bridge.gui.SparMainGUI;

public class HtmlToDatabaseConnector {
	SparMainGUI owner;
	String DBlocation;
	BridgeAccessDAO dao;

	int lastRound = -1;

	public HtmlToDatabaseConnector(SparMainGUI owner)
			throws FileNotFoundException {
		this.owner = owner;
		DBlocation = owner.DBLocation;
		dao = new BridgeAccessDAO(DBlocation);
		lastRound = dao.getLastRoundNumber();
	}

	/**
	 * 
	 * @param string
	 *            JSON string with info to fill the BoardInfoBean
	 * @return a bean with the info from the json string
	 * @throws IOException
	 *             if it cant translate the json string
	 */
	public BoardInfoBean setPlayersOnTableFromJSON(String string)
			throws IOException {
		JSONObject JSON = null;
		try {
			JSON = new JSONObject(string);
		} catch (JSONException e) {
			// crash and burn
			throw new IOException("Error parsing JSON request string");
		}
		BoardInfoBean bi = new BoardInfoBean();
		try {
			bi.fillWithJSON(JSON);
		} catch (JSONException e) {
			System.err.println("JSON in htmltodatabase error");
		}
		bi.setSectionNr(dao.getSectionID(bi.getSection()));
		dao.updatePlayer(bi.getSectionNr(), bi.getTable(), "N", bi.getNorth());
		dao.updatePlayer(bi.getSectionNr(), bi.getTable(), "S", bi.getSouth());
		dao.updatePlayer(bi.getSectionNr(), bi.getTable(), "E", bi.getEast());
		dao.updatePlayer(bi.getSectionNr(), bi.getTable(), "W", bi.getWest());

		return bi;
	}

	/**
	 * finds the names of the players on a table in a round
	 * 
	 * @param bi
	 *            A BoardInfoBean with round, table and section
	 * @return a string with all the names and directions in JSON
	 */

	public String getPlayerNamesAsJSON(BoardInfoBean bi) {
		Vector<PlayerInfoBean> pibV = dao.getPlayerInfoWithName(
				bi.getSection(), Integer.parseInt(bi.getTable()),
				Integer.parseInt(bi.getRound()));
		JSONObject jo = new JSONObject();
		bi = dao.getGameInfo(bi);
		if (checkIfResultsCanBePosted(bi)) {
			try {
				jo.put("name", bi.fileName);
				jo.put("lowBoard", bi.getLowBoard());
				jo.put("highBoard", bi.getHighBoard());
				jo.put("lastRound", lastRound);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			for (int i = 0; i < pibV.size(); i++) {
				PlayerInfoBean p = pibV.get(i);

				try {

					jo.put(p.getPosition(), p.getName());
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return jo.toString();
		} else {
			return null;
		}
	}

	public boolean checkIfResultsCanBePosted(BoardInfoBean bi) {
		boolean canPost = true;
		
		for (int i = bi.getLowBoard(); i <= bi.getHighBoard(); i++){
			if(dao.checkUpdateReceived(bi.getSection(), bi.getTable(), bi.getRound(), ""+i)){
				canPost=false;
				break;
			}
		}
		return canPost;
	}

	/**
	 * inserts the info form the JSONString into the database
	 * 
	 * @param JSONString
	 *            string with info to fill the resultBean
	 * @throws IOException
	 *             if it cant translate the json string
	 */

	public void postingResult(String JSONString) throws IOException {
		JSONObject JSON = null;
		JSONArray JSONarray = null;
		int section = 0;
		try {
			JSON = new JSONObject(JSONString);
			JSONarray = JSON.getJSONArray("allResults");
			section = dao.getSectionID(JSON.getString("section"));
			String round = JSON.getString("round");
			String table = JSON.getString("table");
			for (int i = 0; i < JSONarray.length(); i++) {
				try {
					JSONObject jo = JSONarray.getJSONObject(i);
					String board = (String) jo.get("board");
					String by = (String) jo.get("by");
					String contractNumber = (String) jo.get("contractNumber");
					String contractSuit = (String) jo.get("contractSuit");
					String tricks = (String) jo.get("tricks");
					String redouble = (String) jo.get("redouble");
					ResultBean rB = new ResultBean(section, table, round,
							board, by, contractNumber, contractSuit, tricks,
							redouble);
					dao.insertIntoReceived(rB);
				} catch (JSONException e) {
					System.err.println("---------Postet null");
				}

			}
		} catch (JSONException e) {
			throw new IOException("Error parsing JSON request string");
		}
	}
}
